<template>
  <!-- 系统目录 西成药品 -->
  <div class="MedicenCata">


    <el-tabs type="border-card">
      <el-tab-pane label="患者信息">
        <el-form :model="patientForm" label-width="90px" size="mini" class="compact-form">
          <!-- 第一行 -->
          <el-form-item label="健康ID:">
            <el-input v-model="patientForm.patId" size="mini" :disabled="isInputDisabled" style="width: 150px"
                      @keyup.enter.native="handleSearch" placeholder="输入后回车查询">
            </el-input>
          </el-form-item>

          <el-form-item label="三无:">
            <el-checkbox
                v-model="patientForm.thrNot"
                :true-label="1"
                :false-label="0"
                size="mini">
            </el-checkbox>
          </el-form-item>

          <el-form-item label="姓名:">
            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 1 }" v-model="patientForm.name"
                      :disabled="isInputDisabled" size="mini" style="width: 100%;"></el-input>
          </el-form-item>

          <el-form-item label="性别:">
            <el-select v-model="patientForm.sex" size="mini" style="width: 70px">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select v-model="patientForm.identityCard" size="mini" style="width: 115px" filterable clearable>
              <el-option v-for="item in certypeOption" :key="item.id" :label="item.label"
                         :value="item.id"></el-option>
            </el-select>
            <el-input v-model="patientForm.certno" @blur="certnoMonitor(patientForm)" style="width: 140px"
                      clearable></el-input>
          </el-form-item>

          <el-form-item label="特殊人群:">
            <el-select v-model="patientForm.isSpecial" size="mini" filterable clearable>
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>

          <!-- 第二行 -->
          <el-form-item label="出生日期:">
            <el-date-picker
                v-model="patientForm.brdy"
                type="date"
                size="mini"
                style="width: 140px"
                prefix-icon="none"
                :disabled="true"
                :placeholder="patientForm.identityCard !== 1 ? '' : '身份证自动计算'"
                value-format="yyyy-MM-dd">

            </el-date-picker>
          </el-form-item>

          <el-form-item label="年龄:">
            <div class="age-input-group">
              <el-input v-model="patientForm.ageYear" :disabled="true" size="mini" style="width: 10px;"></el-input>
              <span class="age-unit">岁</span>
              <el-input v-model="patientForm.ageMonth" :disabled="true" size="mini" style="width: 10px;"></el-input>
              <span class="age-unit">月</span>
            </div>
          </el-form-item>

          <el-form-item label="民族:">
            <el-select v-model="patientForm.naty" size="mini" filterable clearable>
              <el-option v-for="item in nationOption" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="职业:">
            <el-select v-model="patientForm.jobId" size="mini" style="width: 130px" filterable clearable>
              <el-option v-for="item in jobOption" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- 第三行 -->
          <el-form-item label="病员费别:">
            <el-select v-model="patientForm.prhCostType" size="mini" style="width: 135px" filterable clearable>
              <el-option v-for="item in this.prhCostOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="病员类型:">
            <el-select v-model="patientForm.prhType" size="mini" style="width: 135px">
              <el-option v-for="item in this.prhTypeOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="合约单位:">
            <!-- 下拉框组件 -->
            <el-select
                v-model="patientForm.phrUnt"
                size="mini"
                filterable
                clearable
                @focus="getContuntList"
            >
              <!-- 默认选项 -->
              <el-option v-for="item in contractUnitOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right">
              <el-button size="mini" type="primary" plain @click.stop="handleEditContractUnit(item)"
                         style="margin-left: 10px">
                修改
              </el-button>
              </span>
              </el-option>
              <el-option :value="undefined" disabled style="cursor: pointer">
                <el-button type="text" @click="handleSaveContractUnit"><i class="el-icon-plus"
                                                                          style="font-weight: bold"></i> 新增合约单位
                </el-button>
              </el-option>
            </el-select>
          </el-form-item>

          <!--        <el-form-item label="次数:">
                    <el-input v-model="patientForm.conerName" size="mini" style="width: 40px"></el-input>
                  </el-form-item>-->

          <el-form-item label="联系人:">
            <el-input v-model="patientForm.conerName" size="mini" style="width: 80px"></el-input>
          </el-form-item>

          <el-form-item label="联系电话:">
            <el-input v-model="patientForm.conerTel" size="mini" style="width: 95px"></el-input>
          </el-form-item>

          <el-form-item label="联系人关系:">
            <el-select v-model="patientForm.conerRltsId" size="mini" filterable clearable style="width: 110px">
              <el-option v-for="item in this.rltsEntitiesOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-row :gutter="15">
            <el-col :span="6">
              <el-form-item label="联系地址:" prop="conerAddName" style="margin-bottom: 8px;">
                <div style="display: flex;">
                  <el-cascader
                      ref="conerAddCodeArrRef"
                      :key="addressKey"
                      v-model="patientForm.conerAddCodeArr"
                      :props="addressProps"
                      :options="provinces"
                      @focus="initAddressData"
                      :placeholder="conerPleasett"
                      style="width: 400px;"
                  />
                  <el-input
                      v-model="patientForm.conerAddName"
                      placeholder="请输入门牌号"
                      style="width: 300px; margin-left: -1px;"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div style="position: relative; height: 30px; margin-left: 15px"
               v-if="permissionsArr.includes('system:docphr:edit')">  <!-- 清除浮动 -->
            <el-button

                type="primary"
                @click="handleEditDocphr"
                size="mini"
                style=" position: absolute; margin-top: 0;"
            >
              修改
            </el-button>
            <el-tooltip
                content="若查询信息不对,可重新填写后点此按钮更改"
                placement="top"
                style="position: absolute; left: 60px; top: 0;"
            >
              <i class="el-icon-question" style="color: #909399; cursor: pointer;"></i>
            </el-tooltip>
          </div>
          <div class="divider-line"></div> <!-- 分隔线 -->
          <el-form-item label="挂号日期:">
            <el-date-picker
                v-model="patientForm.registerDate"
                type="date"
                size="mini"
                style="width: 140px"
                prefix-icon="none"
                @change="loadData"
                :clearable="false"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>

          <!--        <el-form-item label="挂号类别:" class="register-item">
                    <el-select v-model="patientForm.registerType" size="mini" filterable clearable style="width: 200px"
                               @focus="getRegisterType" @change="getRegisterTypeData" @clear="handleCloseRegisterType">
                      <el-option v-for="item in this.registerOptions" :key="item.id" :label="item.label" :value="item.id">
                        <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">金额:{{ item.odcost }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>-->

          <el-form-item label="时段:">
            <el-select v-model="patientForm.timeSlot" size="mini"
                       filterable @change="getTimeFrameData">
              <el-option label="上午" value="1"></el-option>
              <el-option label="下午" value="2"></el-option>
              <el-option label="晚上" value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室:">
            <el-select v-model="patientForm.department" size="mini"
                       filterable clearable @focus="getDeptList" @change="loadData">
              <el-option v-for="item in this.deptOptions" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <!--        <el-form-item label="医生:">
                    <el-select v-model="patientForm.doctor" size="mini" @clear="handleCloseDoctor"
                               filterable clearable @focus="getDoctorList" @change="getDoctorReservation">
                      <el-option v-for="item in this.doctorOptions" :key="item.id" :label="item.label" :value="item.id">
                        <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>-->

        </el-form>
      </el-tab-pane>
    </el-tabs>

    <el-tabs type="border-card">
      <el-tab-pane label="挂号列表">
        <div class="table-container">
          <el-table
              :data="tableData"
              border
              @row-click="handleRowClick"
              highlight-current-row
              style="width: 100%;height: 60%"
              height="100%">
            <el-table-column
                header-align="center"
                align="center"
                v-for="(col, inx) in tableRows"
                :key="inx"
                :type="col.type"
                :prop="col.prop"
                :label="col.name"
                :render-header="labelHead"
                :min-width="getColumnWidth(col.label,col.prop,tableData)">
              <template #default="{ row }">
                {{ safeGetMappedValue(col, row, 0) }}
              </template>
            </el-table-column>
            <el-table-column
                header-align="center"
                fixed="left"
                label="行号"
                type="index"
                width="50px"
                align="center">
            </el-table-column>
          </el-table>
          <div class="custom-dialog-footer" style="padding: 10px 0;">
            <!-- 左侧按钮组 -->
            <div class="left-buttons" style="margin-left: 30px;">
              <!--        <el-button type="primary" @click="handleChoosePatient" size="small" :loading="loading">预约信息</el-button>-->

              <!--        <el-button type="primary" @click="handleChoosePatient" size="small" :loading="loading">换健康卡</el-button>
                      <el-button type="primary" @click="handleChoosePatient" size="small" :loading="loading">发健康卡</el-button>-->
            </div>

            <!-- 右侧按钮组 -->
            <div class="footer-container">
              <div class="footer-buttons">
                <el-button type="primary" @click="handleCelerityFiling" size="small" :loading="loading">快速建档
                </el-button>
                <el-button type="primary" @click="handleCloseForm" size="small" :loading="loading">重建
                </el-button>
                <el-button type="success" :disabled="Object.keys(this.rowData).length === 0" icon="el-icon-check"
                           v-if="permissionsArr.includes('system:register:add')"
                           @click="handleReservationSettle" size="small">结算
                </el-button>
              </div>
            </div>
          </div>
        </div>

      </el-tab-pane>
    </el-tabs>


    <div class="dialog">
      <!--新增往来单位-->
      <el-dialog :title="addUnitForm.id  == null ?'新增合约单位':'修改合约单位'" :before-close="handleCancelContract"
                 :visible.sync="addUnitModalVisible" class="addUnitDialog" width="50%" :close-on-click-modal="false">
        <div class="aform">
          <!-- 表单 -->
          <el-form :model="addForm" label-width="90px" size="mini" :rules="addUnitRules" ref="addUnitRef">
            <el-row :gutter="20">
              <el-col :span="v.spanRows" type="flex" v-for="(v,i) in addUnitType" :key="i"
                      :style="{ marginLeft: v.modelValue === 'uscc' ? '18px' : '0' }">
                <!-- input -->
                <el-form-item v-if="v.type === 'input'" :required="['code', 'name'].includes(v.modelValue)"
                              :label="v.label" :style="v.modelValue === 'uscc' ? 'white-space: nowrap' : ''">
                  <el-input :suffix-icon='v.prefix' v-model="$data.addUnitForm[v.modelValue]"
                            @input="handleNameChangeCode(v,i)"
                            :style="{ marginLeft: v.modelValue === 'uscc' ? '30px' : '0' }">

                  </el-input>
                </el-form-item>
                <!-- select -->
                <el-form-item v-if="v.type === 'select'" :label="v.label">
                  <el-select v-model="$data.addUnitForm[v.modelValue]" filterable
                             :disabled="v.modelValue === 'untAtte'">
                    <el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
                      <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 新增的按钮区域 - 并排显示（添加在前，取消在后） -->
            <el-form-item style="margin-top: 20px; text-align: right">
              <el-button type="primary" size="mini" @click="handleAddContractUnit">
                {{ addUnitForm.id == null ? '新增' : '修改' }}
              </el-button>
              <el-button size="mini" @click="handleCancelContract" style="margin-left: 10px">取消</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-dialog>

      <!--挂号支付窗口-->
      <el-dialog
          title="挂号支付"
          :visible.sync="addModalVisible"
          width="800px"
          :close-on-click-modal="false"
          class="payment-dialog"
      >
        <el-form :model="addForm" label-width="100px" class="payment-form">
          <!-- 上半部分：金额信息 -->
          <div class="form-section">
            <!-- 第一排：3个字段 -->
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="应收金额:">
                  <el-input size="mini" v-model="patientForm.total" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="当前票号:">
                  <el-input size="mini" v-model="patientForm.currentNumber" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="账户余额:">
                  <el-input size="mini" v-model="patientForm.balance" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二排：2个字段 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="挂账余额:">
                  <el-input size="mini" v-model="addForm.credit" value="0/0" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="留观金额:">
                  <el-input size="mini" v-model="addForm.observation" value="0" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 备注单独一行 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:">
                  <el-input size="mini" type="textarea" v-model="addForm.remarks"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="form-section">
            <!-- 第一行：病员费别 + 现金支付 + 医保支付 -->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="病员费别:" class="payment-item">
                  <el-select size="mini" v-model="patientForm.prhCostType"
                             clearable disabled>
                    <el-option v-for="item in prhCostOption" :key="item.id" :label="item.label"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="现金支付:" class="payment-item">
                  <el-input type="number" min="0" size="mini" v-model="addForm.cashAmt"
                            :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="医保支付:" class="payment-item">
                  <el-input @input="calculatePayments" type="number" min="0" size="mini"
                            v-model="addForm.chsAmt"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行：健康卡付 + 银联支付 + 优惠金额 -->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="健康卡付:" class="payment-item">
                  <el-input @input="calculatePayments" type="number" min="0" size="mini" v-model="addForm.patAmt"
                            :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="银联支付:" class="payment-item">
                  <el-input @input="calculatePayments" type="number" min="0" size="mini" :disabled="true"
                            v-model="addForm.bankAmt"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="优惠金额:" class="payment-item">
                  <el-input @input="calculatePayments" type="number" min="0" size="mini" :disabled="true"
                            v-model="addForm.distAmt"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行：挂账支付 + 网络支付 + 留观预交  payTypeOption-->
            <el-row :gutter="20" class="payment-row">
              <el-col :span="8">
                <el-form-item label="挂账支付:" class="payment-item">
                  <el-input @input="calculatePayments" disabled type="number" min="0" size="mini"
                            v-model="addForm.bebtAmt"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item class="payment-item" label="网络支付:">
                  <!-- 替换 label 的下拉框 -->
                  <!--                  <el-select
                                        v-model="paymentForm.opeWay"
                                        size="mini"
                                        clearable
                                        placeholder="支付方式"
                                        style="width: 83px; margin-left: -83px"
                                    >
                                      <el-option
                                          v-for="item in payTypeOption"
                                          :key="item.id"
                                          :label="item.label"
                                          :value="item.id"
                                      />
                                    </el-select>-->

                  <!-- 原来的输入框 -->
                  <el-input @input="calculatePayments" min="0" type="number" size="mini" v-model="addForm.groupAmt"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="留观预交:" class="payment-item">
                  <el-input @input="calculatePayments" size="mini" v-model="addForm.observationAdvance"
                            :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 结算信息 -->
            <div class="payment-summary">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="应付金额:" class="compact-item">
                    <span class="amount">{{ addForm.currentTotal }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="收到金额:" class="compact-item">
                    <el-input @input="calculatePayments" ref="recdAmt" size="mini" v-model="addForm.recdAmt"
                              class="compact-input"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="应退找零金额:" class="compact-item">
                    <span class="amount">{{ addForm.change }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>

          <!-- 按钮组 -->
          <div class="form-actions">
            <!--            <el-button type="text">查看优惠明细</el-button>
                        <el-button>打印发票</el-button>-->
            <el-button type="primary" @click="handleConfirmPay">确认支付</el-button>
            <el-button type="warning" @click="handleCloseConfirmPay">退出支付</el-button>
          </div>
        </el-form>
      </el-dialog>

      <!--患者选择-->
      <el-dialog
          title="患者选择"
          :visible.sync="patientDialogVisible"
          width="60%"
          :before-close="handleCloseChoosePatient"
          class="patient-dialog"
      >
        <!-- 患者表格 - 固定高度，超出部分滚动 -->
        <el-table
            :data="patientTabelData"
            border
            highlight-current-row
            @row-dblclick="handleChoosePatient"
            @current-change="handleClickRow"
            style="width: 100%;"
            height="400px"
        >
          <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" :render-header="labelHead" align="center"
                           :min-width="getColumnWidth(col.label,col.prop,patientTabelData)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="dialog-footer no-line">
          <el-button @click="handleCloseChoosePatient" size="mini">取消</el-button>
          <el-button type="primary" @click="handleChoosePatient" size="mini" :loading="loading">确定</el-button>
        </div>
      </el-dialog>

      <!--快速建档-->
      <el-dialog
          :close-on-click-modal="false"
          title="快速建档-新增健康档案"
          :visible.sync="celerityFilingDialogVisible"
          width="50%"
          @close="handleCloseCelerityFiling"
          class="patient-dialog"
      >
        <el-form :model="celerityFilingForm" ref="celerityFilingFormRef" :rules="celerityFilingFormRules"
                 label-width="90px" size="mini" class="compact-form">

          <!-- 第一行 -->
          <el-form-item label="姓名:" prop="name">
            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 1 }" v-model="celerityFilingForm.name"
                      size="mini" style="width: 100%;"></el-input>
          </el-form-item>

          <el-form-item label="性别:" prop="sex">
            <el-select v-model="celerityFilingForm.sex" size="mini" style="width: 70px">
              <el-option label="男" value="1"></el-option>
              <el-option label="女" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="identityCard">
            <el-select v-model="celerityFilingForm.identityCard" @input="" size="mini" style="width: 115px" filterable
                       clearable>
              <el-option v-for="item in certypeOption" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
            <el-input v-model="celerityFilingForm.certno" prop="certno" style="width: 200px"
                      @blur="certnoMonitor(celerityFilingForm)"
                      clearable :maxlength="certLengthMap[celerityFilingForm.identityCard]" show-word-limit/>
          </el-form-item>

          <el-form-item label="三无:" prop="thrNot">
            <el-checkbox
                v-model="celerityFilingForm.thrNot"
                :true-label="1"
                :false-label="0"
                @change="handleThrNotChange"
                size="mini">
            </el-checkbox>
          </el-form-item>

          <!-- 第二行 -->
          <el-form-item label="出生日期:" prop="brdy">
            <el-date-picker
                v-model="celerityFilingForm.brdy"
                type="date"
                size="mini"
                style="width: 140px"
                :disabled="celerityFilingForm.identityCard === 1"
                prefix-icon="none"
                :placeholder="celerityFilingForm.identityCard === 1 ? '' : '身份证自动计算'"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="年龄:" prop="ageYear" style="margin-left: 20px;">
            <div class="age-input-group">
              <el-input
                  v-model="celerityFilingForm.ageYear"
                  :disabled="celerityFilingForm.identityCard === 1"
                  size="mini"
                  style="width: 40px;"
              />
              <span class="age-unit">岁</span>
              <el-input
                  v-model="celerityFilingForm.ageMonth"
                  prop="ageMonth"
                  :disabled="true"
                  size="mini"
                  style="width: 40px;"
              />
              <span class="age-unit">月</span>
            </div>
          </el-form-item>

          <el-form-item label="国籍:" prop="ntlyId">
            <el-select v-model="celerityFilingForm.ntlyId" size="mini" filterable clearable>
              <el-option v-for="item in ntlyOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="民族:" prop="naty">
            <el-select v-model="celerityFilingForm.naty" size="mini" filterable clearable>
              <el-option v-for="item in nationOption" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="职业:" prop="jobId">
            <el-select v-model="celerityFilingForm.jobId" size="mini" style="width: 130px" filterable clearable>
              <el-option v-for="item in jobOption" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="病员类型:" prop="prhType">
            <el-select v-model="celerityFilingForm.prhType" size="mini" style="width: 135px">
              <el-option v-for="item in this.prhTypeOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="合约单位:" prop="phrUnt">
            <el-select
                v-model="celerityFilingForm.phrUnt"
                size="mini"
                filterable
                clearable
                @focus="getContuntList"
            >
              <el-option v-for="item in contractUnitOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right">
          <el-button size="mini" type="primary" plain @click.stop="handleEditContractUnit(item)"
                     style="margin-left: 10px">
            保存
          </el-button>
          <el-tooltip content="若查询信息不对,可重新填写后点此按钮更改" placement="top" style="margin-left: 8px;">
            <i class="el-icon-question" style="color: #909399; cursor: pointer;"></i>
          </el-tooltip>
        </span>
              </el-option>
              <el-option :value="undefined" disabled style="cursor: pointer">
                <el-button type="text" @click="handleSaveContractUnit">
                  <i class="el-icon-plus" style="font-weight: bold"></i> 新增合约单位
                </el-button>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="联系人:" prop="conerName">
            <el-input v-model="celerityFilingForm.conerName" size="mini" style="width: 80px"></el-input>
          </el-form-item>

          <el-form-item label="联系电话:" prop="conerTel">
            <el-input v-model="celerityFilingForm.conerTel" size="mini" style="width: 95px"></el-input>
          </el-form-item>

          <el-form-item label="联系人关系:" prop="conerRltsId">
            <el-select v-model="celerityFilingForm.conerRltsId" size="mini" filterable clearable style="width: 110px">
              <el-option v-for="item in this.rltsEntitiesOption" :key="item.id" :label="item.label" :value="item.id">
                <span style="float: center; color: #8492a6; font-size: 12px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="联系地址:" prop="conerAddName" style="margin-bottom: 8px; width: 100%">
            <div style="display: flex;">
              <el-cascader
                  ref="conerAddCodeArrRef"
                  :key="addressKey"
                  v-model="celerityFilingForm.conerAddCodeArr"
                  :props="addressProps"
                  :options="provinces"
                  @focus="initAddressData"
                  style="width: 400px;"
              />
              <el-input
                  v-model="celerityFilingForm.conerAddName"
                  placeholder="请输入门牌号"
                  style="width: 100%; margin-left: -1px;"
              />
            </div>
          </el-form-item>

        </el-form>
        <div class="celerity-filing-button" style="margin-left: 100px;">
          <el-button size="mini" type="warning" @click="handleResetContract">
            重置
          </el-button>
          <el-button type="primary" @click="handleIdCardData" size="mini">身份证读取</el-button>
          <el-button type="primary" @click="handleAddCelerityFiling" size="mini">保存</el-button>
          <el-button @click="handleCloseCelerityFiling" size="mini">取消</el-button>
        </div>
      </el-dialog>


      <!--付款码支付窗口-->
      <el-dialog
          title="请扫描患者付款码"
          :visible.sync="payModalVisible"
          width="30%"
          :close-on-click-modal="false"
          @opened="handlePayDialogOpened"
          @closed="handlePayDialogClosed">

        <!-- 隐藏的扫码输入框 -->
        <div style="position: absolute; left: -9999px;">
          <el-input
              ref="paymentCodeInput"
              v-model="paymentCode"
              @input="handleScanComplete">
          </el-input>
        </div>

        <!-- 可视化提示区域 -->
        <div style="text-align: center; padding: 20px 0;">
          <!-- 状态1：等待扫码 -->
          <template v-if="scanStatus === 'waiting'">
            <i class="el-icon-loading" style="font-size: 40px;"></i>
            <p style="margin-top: 15px;">请使用扫码枪扫描顾客付款码</p>
          </template>

          <!-- 状态2：处理中 -->
          <template v-else-if="scanStatus === 'processing'">
            <i class="el-icon-loading" style="font-size: 40px;"></i>
            <p style="margin-top: 15px;">正在处理付款请求...</p>
          </template>

          <!-- 状态3：处理成功 -->
          <template v-else-if="scanStatus === 'success'">
            <i class="el-icon-success" style="font-size: 40px; color: #67C23A;"></i>
            <p style="margin-top: 15px;">
              付款成功！{{ countdown }}秒后自动关闭
            </p>
            <el-progress
                :percentage="countdown * 20"
                status="success"
                style="width: 80%; margin: 10px auto;"
            ></el-progress>
          </template>

          <template v-else-if="scanStatus === 'error'">
            <i class="el-icon-error" style="font-size: 40px; color: #F56C6C;"></i>
            <p style="margin-top: 15px;">{{ errorMessage }}</p>
            <p style="margin-top: 10px; color: #999;">{{ countdown }}秒后重新开始扫码</p>
            <el-progress
                :percentage="countdown * 20"
                status="exception"
                style="width: 80%; margin: 10px auto;"
            ></el-progress>
          </template>
        </div>
      </el-dialog>
    </div>


  </div>
</template>

<script>

import {
  addContractUnit,
  addDocphr,
  addRegisterList,
  dict,
  editContractUnit,
  editDocphr,
  getActiveList,
  getArea,
  getConsultingDepartment,
  getContractUnit,
  getContuntList,
  getDeptOfDoctor,
  getDocphrList,
  getDoctorList,
  getRegisterType
} from "@/api/reservation/reservation";
import AddType from './reservationAddType.js'
import AddType2 from './reservationSettleType.js'
import {pinyin} from "pinyin-pro";
import AddressSelector from "@/views/reservation/AddressSelector.vue";
import {sqbPayment} from "@/api/reservation/outpatientCharge";
import dayjs from "dayjs";
import {getDoesItExistSFZ} from "@/api/reservation/outpatientPhysician";
import {readIdCard} from "@/untils/idCardReader";
import {getNationalityId} from "@/untils/outpatientPhysicianUntils";
import {withLoading} from "@/untils/loading";
import {addYbResponseData, addYbresponseData, addYbRquestData, getqdNo} from "@/api/yb";
import {buildYbRequest, generateYbHeaders, sendYbRequest} from "@/api/yb/ybApi";

export default {
  components: {AddressSelector},
  data() {
    return {
      activeTab: 'patientInfo',
      conerPleasett: '',
      addressKey: null,
      certLengthMap: {
        1: 18,  // 居民身份证
        2: 20,  // 居民户口簿
        3: 9,   // 护照
        4: 10,  // 军官证
        5: 12,  // 驾驶证
        6: 11,  // 港澳居民来往内地通行证
        7: 10,  // 台湾居民来往内地通行证
        8: 18,  // 中国人民武装警察身份证件
        9: 20   // 其他法定有效证件
      },
      // 证件格式验证规则
      certPatterns: {
        1: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
        2: /^[A-Za-z0-9\u4e00-\u9fa5]{1,20}$/,
        3: /^[A-Za-z]\d{7,8}$/,
        4: /^[A-Za-z0-9\u4e00-\u9fa5]{1,10}$/,
        5: /^\d{12}$/,
        6: /^[HMhm]\d{8,10}$/,
        7: /^\d{8}[A-Za-z]{2}$/,
        8: /^WJ\d{6}\d{11}$/,
        9: /^[A-Za-z0-9\u4e00-\u9fa5]{1,20}$/
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      selectedValues: [],
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      pageDataState: null,
      addcategory: [],
      itemPriceOptions: [],
      patientDialogVisible: false,
      patientTabelData: [],
      loading: false,
      addModalVisible: false,
      isInputDisabled: false,
      celerityFilingDialogVisible: false,
      payModalVisible: false,
      paymentCode: '',//支付码
      terminalId: null,//系统序号
      scanTimer: null,//防抖
      isProcessing: false,//支付判断
      isSuccess: false,//支付判断
      scanStatus: 'waiting', // waiting|processing|success
      errorMessage: '付款失败,请重试', // waiting|processing|success
      resetTimer: null,
      countdown: 5, // 倒计时秒数
      countdownInterval: null, // 倒计时定时器
      orderId: 32,//回调订单ID
      countdownStartTime: 0,    // 记录倒计时开始时间
      animationFrameId: null,   // 存储动画帧ID
      userInfo: null,   // 存储动画帧ID


      unitStateOption: [{id: 1, label: '启用'}, {id: 0, label: '禁用'}],
      areaOption: [{id: 1, label: '省内'}, {id: 2, label: '省外'}, {id: 3, label: '进口'}],

      elTree: [{label: '全部'}],
      tableRows: [
        {name: "科室名称", prop: "deptName", type: ""},
        {name: "医生姓名", prop: "doctorName", type: ""}, {name: "职称", prop: "professionalTitle", type: ""},
        {name: "挂号类别", prop: "registertypeName", type: ""},
        {name: "挂号金额", prop: "price", type: ""},
        {name: "上午时段", prop: "amTime", type: ""},
        {name: "下午时段", prop: "pmTime", type: ""},
        {name: "晚上时段", prop: "nightTime", type: ""},
        {name: "限号", prop: "limitNum", type: ""},
        {name: "余号", prop: "remainingNum", type: ""},
        {name: "已挂", prop: "useNum", nz: "nz"},
      ],
      tableRows2: [
        {name: "健康ID", prop: "id"},
        {name: "健康卡号", prop: "patId"},
        {name: "姓名", prop: "name"},
        {name: "身份证号", prop: "certno"},
        {name: "联系电话", prop: "conerTel"},
      ],
      tableData: [],
      provinces: [],  // 所有省份
      cityOption: [],     // 当前省下的城市
      countyOption: [],    // 当前市下的区县
      townOption: [],    // 区县下的乡
      villageOption: [],    // 区县下的乡
      prhCostOption: [],//病员费别
      prhTypeOption: [],//病员类别
      rltsEntitiesOption: [],//联系人关系
      jobOption: [],//联系人关系
      contractUnitOption: [],//合约单位
      untAtteOption: [],//往来单位新增---单位属性
      deptOptions: [],//科室下拉框
      doctorOptions: [],//医生下拉框
      registerOptions: [],//挂号类别
      ntlyOptions: [],//国籍
      addUnitForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },
      addUnitType: [],
      addType: [],
      nationOption: [],//民族下拉框
      certypeOption: [],//证件下拉框
      profttlOption: [],//职业下拉框
      feeTypeOption: [],//病案费别下拉框
      payTypeOption: [{id: 1, label: '现金'}, {id: 2, label: '支付宝'}, {id: 3, label: '微信'}, {
        id: 4,
        label: '银行卡'
      }, {id: 5, label: '医保'}, {id: 6, label: '优惠支付'}, {id: 7, label: '健康卡支付'}],
      patientChooseForm: {
        id: null,
        patId: '',
        name: '',
        sex: null,
        certno: null,
        conerTel: null,
        contractUnit: null,
        healthCardNo: null,
        cardType: null,
      },
      addForm: {
        discountMoney: null,
        name: '',
        patientId: null,
        payType: null,
        receivableMoney: null,
        receivedMoney: null,
        regDepId: null,
        regDoctorId: null,
        regMode: null,
        regNum: null,
        regTypeId: null,
        regUserId: null,
        remake: '',
        utyTimeDetailsId: null,
        visitId: null,
        rgstId: null,
        /**/
        accountNumber: null,
        currentNumber: null,
        oweNumber: '0/0',
        remark: null,
        feeType: null,
        MoneyPay: null,
        healthCarePay: null,
        fitnessCardpa: null,
        unionPay: null,
        owePay: null,
        phonePay: null,
        discountsNumb: null,
        receivableNum: null,
        receiveNumber: null,
        changeNumber: null,
        remarks: null,
        cashAmt: null,//现金支付
        currentTotal: null,//应付金额
        recdAmt: null,//收到金额
        chsAmt: null,//医保
        credit: null,//挂账余额
        observation: null,//留观金额
        patAmt: null,//健康卡支付
        bankAmt: null,//银联支付
        distAmt: null,//优惠金额
        bebtAmt: null,//挂账支付
        groupAmt: null,//网络支付
        observationAdvance: null,//留观预交金
        change: null,//应退找零金额
        age: null,
      },
      addUnitModalVisible: false, // 布尔值，控制模态框显示
      newUnitForm: {name: ''},// 存储表单数据
      rowData: {},
      addressProps: {
        lazy: true,
        value: 'areaCode',
        label: 'areaName',
        emitPath: true,
        leaf: node => node.areaLevel >= 5, // 第五级是叶子节点
        lazyLoad: async (node, resolve) => {
          try {
            const level = node.level + 1;

            // 限制最大层级为5
            if (level > 5) {
              return resolve([]);
            }

            // 请求参数
            const params = {
              areaCode: node.level > 0 ? node.data.areaCode : undefined,
              areaLevel: level,
              condtion: ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code', 'area_t_code'][level - 1]
            };

            const res = await getArea(params);
            const responseData = res?.data || [];

            // 如果没有数据，关闭下拉框
            if (responseData.length === 0 && level > 1) {
              this.handleCloseCascader();
            }

            // 格式化数据（关键修改：添加 isLeaf 和 level 属性）
            const formattedData = responseData.map(item => ({
              ...item,
              value: item.areaCode, // 严格模式需要 value 字段
              label: item.areaName,
              level: level, // 标记当前层级
              isLeaf: level >= 5 // 第五级强制设为叶子节点
            }));

            resolve(formattedData);

          } catch (error) {
            console.error('加载地区数据失败:', error);
            resolve([]);
          }
        }
      },

      categoryOptions: [],
      showContactAddressInput: false,
      patientForm: {
        id: null,
        patId: '',       // 健康ID
        thrNot: false,   // 三无（复选框应为布尔值）
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: null,        // 年龄-岁
        ageMonth: null,       // 年龄-月
        naty: '汉族',     // 民族
        jobId: null,            // 职业
        feeType: null, // 病员费别
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        isSpecial: '否',    // 特殊人群
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        registerDate: dayjs().format('YYYY-MM-DD'),
        timeSlot: this.getCurrentTimeSlot(),      // 时段
        department: null,     // 科室
        doctor: null,         // 医生
        registerType: null,   // 挂号类别
        clinicRoom: null,  // 诊室
        existNumber: null,
        currentNumber: null,
        caseHistory: null,
        total: null,//
        naplAddCode: null,
        conerAddCode: null,
        number: null,
        conerAddName: null,
        conerAddCodeArr: [],
        phrUnt: null,
        prhCostType: null,
      },
      celerityFilingForm: {
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: null,        // 年龄-岁
        ageMonth: null,       // 年龄-月
        ageDay: 0,       // 年龄-天
        naty: 1,     // 民族
        ntlyId: 1,    //国籍
        jobId: '',            // 职业
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        tel: null,
        restAddCode: null,
        naplAddCode: null,
        conerAddCodeArr: [],
        conerAddName: '',
        thrNot: null,
        phrUnt: null,
      },

      celerityFilingFormRules: {
        name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('姓名不能为空'));
              callback();
            },
            trigger: 'blur'
          }
        ],
        sex: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择性别'));
              callback();
            },
            trigger: 'change'
          }
        ],
        certno: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('证件号码不能为空'));
              callback();
            },
            trigger: 'blur'
          }
        ],
        brdy: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('出生日期不能为空'));
              callback();
            },
            trigger: 'change'
          }
        ],
        ntlyId: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择国籍'));
              callback();
            },
            trigger: 'change'
          }
        ],
        naty: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择民族'));
              callback();
            },
            trigger: 'change'
          }
        ],
        jobId: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择职业'));
              callback();
            },
            trigger: 'change'
          }
        ],
        prhType: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择病员类型'));
              callback();
            },
            trigger: 'change'
          }
        ],
        conerName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('联系人不能为空'));
              callback();
            },
            trigger: 'blur'
          }
        ],
        conerTel: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('联系电话不能为空'));
              // 电话号码格式验证
              const mobileReg = /^1[3-9]\d{9}$/;
              const telReg = /^0\d{2,3}-\d{7,8}$/;
              if (!mobileReg.test(value) && !telReg.test(value)) {
                return callback(new Error('请输入正确的电话号码'));
              }
              callback();
            },
            trigger: 'blur'
          }
        ],
        conerRltsId: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('请选择联系人关系'));
              callback();
            },
            trigger: 'change'
          }
        ],
        conerAddName: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.celerityFilingForm.thrNot === 1) return callback();
              if (!value) return callback(new Error('联系地址不能为空'));
              callback();
            },
            trigger: 'blur'
          }
        ]
      },
      addUnitRules: {
        code: [{required: true, message: '请填写合约单位编码！', trigger: 'change'}],
        name: [{required: true, message: '请填写合约单位名称！', trigger: 'change'}],
      },
      permissionsArr: [],
    };
  },
  watch: {
    'addForm.cashAmt'(newVal) {
      this.updatePayType();
    },
    'addForm.recdAmt'(newVal) {
      this.updatePayType();
    },
    'patientForm.conerRltsId'(newVal) {
      if (newVal === '') {
        this.patientForm.conerRltsId = null;
      }
    },
  },
  beforeDestroy() {
    // 组件销毁时移除监听，避免内存泄漏
    window.removeEventListener('keydown', this.handleKeyPress);
  },
  async mounted() {
    this.addUnitType = AddType.map(function (v) {
      return v
    })

    window.addEventListener('keydown', this.handleKeyPress);
    this.addType = AddType2.map(function (v) {
      return v
    })
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    await this.dict();
    await this.getContuntList();
    await this.loadData();
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
    this.updateTimeSlot();
    await this.handleGetPatientYbInfo();
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },
  methods: {
    async handleGetPatientYbInfo() {
      //1.获取签到编号
      const {data: {signNo}} = await getqdNo();

      //2.构造请求参数
      const ybTemplate = buildYbRequest(signNo, '1101');
      ybTemplate.body.input.data = {
        mdtrt_cert_type: "02",
        mdtrt_cert_no: "532129199809102314",
        card_sn: "",
        psn_cert_type: "01",
        certno: "532129199809102314",
        psn_name: "",
      };

      //3.发送后端进行请求备份
      const res = await addYbRquestData({
        infno: '1101',
        mdtrtareaAdmvs: this.userInfo.mdtrtareaAdmvs,
        data: JSON.stringify(ybTemplate),
        patientId: this.userInfo.staffId,
        patientName: this.userInfo.staffName
      })
      if (res.code === 200) {
        //4.1组装请求头数据
        const headers = generateYbHeaders({
          infosyscode: res.data.infosyscode,
          signature: res.data.signature,
          clinicCode: this.userInfo.clinicCode,
          hsfNonce: res.data.hsfNonce,
          hsfTimestamp: res.data.hsfTimestamp
        })
        //4.2发送医保
        const ybResponse = await sendYbRequest(ybTemplate.body, headers);
        addYbResponseData({id:res.data.id,infno:'1101',data:JSON.stringify(ybResponse)});
        if (ybResponse.infcode === -1) {
          this.$message.error(ybResponse.err_msg)
        }
      } else {
        this.$message.error(res.message)
      }

    },
    handleKeyPress(event) {
      // 检查是否为 F9 键（兼容 key 和 keyCode）
      if (event.key === 'F9' || event.keyCode === 120) {
        event.preventDefault(); // 阻止默认行为
        this.handleIdCardData(); // 调用你的业务方法
      }
    },
    async handleIdCardData() {
      await withLoading(this, '身份证读取中...')(async () => {
        try {
          const res = await readIdCard();
          if (this.celerityFilingDialogVisible) {
            if (this.celerityFilingForm.certno && this.celerityFilingForm.certno.trim() !== '') {
              return;
            }

            this.celerityFilingForm.certno = res.cardno;
            this.celerityFilingForm.name = res.name;
            this.celerityFilingForm.naty = getNationalityId(this.ntlyOptions, res.nation) ?? 1;
            const isExist = await this.certnoMonitor(this.celerityFilingForm);
            if (isExist === 1) {
              this.patientForm.patId = res.cardno;
              await this.handleSearch();
              this.$message.warning("已自动匹配患者存在信息")
              this.celerityFilingDialogVisible = false;
            }
          } else {
            this.patientForm.patId = res.cardno;
            await this.handleSearch();
          }

        } catch (error) {
          this.$message.error(error || '处理身份证数据时出错');
        }
      });
    },

    async loadAndDisplayAddress(type = 'coner') {
      try {
        // 1. 确保省级数据已加载
        if (this.provinces.length === 0) {
          await this.loadProvincial();
        }

        // 2. 根据地址类型获取对应数据
        const codeKey = `${type}AddCodeArr`;
        const nameKey = `${type}AddName`;
        const codes = this.patientForm[codeKey] || [];

        let currentNodes = this.provinces;
        const loadedCodes = [];
        const addressNames = [];
        const levelConditions = ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code', 'area_t_code'];

        // 3. 按层级逐级加载
        for (let i = 0; i < codes.length; i++) {
          const code = codes[i];
          const level = i + 1; // 1:省, 2:市, 3:县, 4:镇, 5:乡

          // 尝试从当前层级查找节点
          let targetNode = currentNodes.find(node => node.areaCode === code);

          // 如果未找到，尝试动态加载该级数据
          if (!targetNode) {
            const parentCode = i > 0 ? codes[i - 1] : undefined;
            const params = {
              areaCode: parentCode,
              areaLevel: level,
              condtion: levelConditions[i]
            };

            const res = await getArea(params);
            currentNodes = res.data || [];
            targetNode = currentNodes.find(node => node.areaCode === code);

            // 如果是省级数据，更新this.provinces
            if (level === 1) {
              this.provinces = currentNodes;
            }
          }

          if (!targetNode) {
            break;
          }

          loadedCodes.push(code);
          addressNames.push(targetNode.areaName);
          // 动态加载子级数据（如果未到末级）
          if (!targetNode.leaf && level < 5) {
            const res = await getArea({
              areaCode: code,
              areaLevel: level + 1,
              condtion: levelConditions[level]
            });
            targetNode.children = res.data || [];
            currentNodes = targetNode.children;
          }
        }
        if (type === 'coner') {
          this.patientForm.conerAddJoinName = addressNames.join('');
        }
        this.$nextTick(() => {
          // 先强制清空以触发响应式更新
          this.patientForm[codeKey] = [];

          // 立即重新赋值（不再使用setTimeout）
          this.$nextTick(() => {
            this.patientForm[codeKey] = [...loadedCodes];
            console.log(this.patientForm, 'this.patientFormthis.patientFormthis.patientForm')
            // 调用内部方法强制更新显示文本
            if (type === "coner") {
              this.conerPleasett = addressNames.join('/');
            } else {
              this.naplPleasett = addressNames.join('/');
            }
            this.addressKey = Date.now(); // 通过key强制刷新组件
          });
        });
      } catch (error) {
        console.error(`加载${type}地址数据失败:`, error);
        this.$message.error('地址加载失败，请重试');
      }
    },
    async loadSelectedPath() {
      try {
        if (this.provinces.length === 0) {
          await this.loadProvincial();
        }

        const codes = this.patientForm.conerAddCodeArr || [];
        const levelConditions = ['area_p_code', 'area_p_code', 'area_c_code', 'area_d_code'];
        let currentNodes = this.provinces;
        const loadedCodes = [];

        for (let i = 0; i < codes.length; i++) {
          const code = codes[i];
          const level = i + 1;

          let node = currentNodes.find(n => n.areaCode === code);
          if (!node) {
            const res = await getArea({
              areaCode: i > 0 ? codes[i - 1] : undefined,
              areaLevel: level,
              condtion: levelConditions[i]
            });
            currentNodes = res.data || [];
            node = currentNodes.find(n => n.areaCode === code);
            if (level === 1) this.provinces = currentNodes;
          }

          if (!node) break;
          loadedCodes.push(code);

          if (level < 4 && (!node.children || node.children.length === 0)) {
            const res = await getArea({
              areaCode: code,
              areaLevel: level + 1,
              condtion: levelConditions[level]
            });
            node.children = res.data || [];
          }

          currentNodes = node.children || [];
        }

        this.patientForm.conerAddCodeArr = [...loadedCodes];

      } catch (error) {
        console.error('地址路径加载失败:', error);
      }
    },
    async initAddressData() {
      if (this.provinces.length === 0) {
        await this.loadProvincial();
      }
      await this.loadSelectedPath();
    },

    // 加载省级数据
    async loadProvincial() {
      try {
        const res = await getArea({
          areaLevel: 1,
          condtion: 'area_p_code'
        });
        this.provinces = res.data.map(item => ({
          areaCode: item.areaCode,
          areaName: item.areaName,
          leaf: false
        }));
        console.log(this.provinces, 'this.provincesthis.provinces')
      } catch (error) {
        console.error('加载省级数据失败:', error);
      }
    },


    handleCloseCelerityFiling() {
      this.handleResetContract();
      this.celerityFilingDialogVisible = false;
    },

    handleResetContract() {
      this.celerityFilingForm = Object.assign({}, this.$options.data.call(this).celerityFilingForm);
      this.$refs.celerityFilingFormRef.resetFields();
    },

    getCurrentTimeSlot() {
      const hour = dayjs().hour();
      if (hour >= 6 && hour < 12) {
        return '1'; // 上午
      } else if (hour >= 12 && hour < 18) {
        return '2'; // 下午
      } else {
        return '3'; // 晚上
      }
    },
    handleCloseChoosePatient() {
      this.patientDialogVisible = false;
      this.isInputDisabled = false;
    },

    async handleThrNotChange() {
      const today = dayjs().format('YYYYMMDD');
      // 生成4个随机大写字母
      const randomChars = Array.from({length: 5}, () =>
          String.fromCharCode(65 + Math.floor(Math.random() * 26))
      ).join('');

      this.celerityFilingForm.name = `三无人员${today}_${randomChars}`;
    },

    handleClosePayData() {
      this.patientForm = Object.assign({}, this.$options.data.call(this).paymentForm);
      this.addForm = Object.assign({}, this.$options.data.call(this).addForm);
      this.tableData = [];
      this.payModalVisible = false;
      this.addModalVisible = false;
    },

    updatePayType() {
      if (Number(this.addForm.cashAmt) && Number(this.addForm.groupAmt)) {
        this.addForm.payType = 9;
      } else if (Number(this.addForm.cashAmt) === Number(this.patientForm.total)) {
        this.addForm.payType = 1;
      } else if (Number(this.addForm.groupAmt) === Number(this.patientForm.total)) {
        this.addForm.payType = 8;
      }
    },
    startCountdown() {
      // 清除现有动画帧和定时器
      cancelAnimationFrame(this.animationFrameId);
      clearInterval(this.countdownInterval);

      // 初始化倒计时
      this.countdown = 5;
      this.countdownStartTime = Date.now();

      // 启动动画帧循环
      const animate = () => {
        const elapsed = Date.now() - this.countdownStartTime;
        const remaining = Math.max(0, 5 - Math.floor(elapsed / 1000));

        // 更新显示
        this.countdown = remaining;

        if (remaining > 0) {
          // 继续下一帧
          this.animationFrameId = requestAnimationFrame(animate);
        } else {
          // 倒计时结束
          if (this.scanStatus === 'success') {
            this.handleClosePayData();
          }
          this.resetScanner();
        }
      };

      this.animationFrameId = requestAnimationFrame(animate);
    },
    handlePaymentError() {
      this.scanStatus = 'error';
      this.startCountdown();
      this.$message.error('支付处理失败');
    },
    async processPayment(code) {
      this.scanStatus = 'processing';

      try {
        const res1 = await sqbPayment({dynamicId: code, orderId: this.orderId});

        // 处理支付结果
        if (res1.data === 'PAY_SUCCESS') {
          this.scanStatus = 'success';
          // 支付成功
          this.startCountdown();
        } else if (res1.data === 'PAY_IN_PROGRESS') {
          this.scanStatus = 'processing';
          // 支付中，开始轮询
          await this.pollPaymentStatus(20); // 最多轮询20次
        } else if (res1.data === 'PAY_ERROR') {
          this.scanStatus = 'error';
          // 支付失败
          this.handlePaymentError();
        }

      } catch (error) {
        // 网络或系统错误
        this.handlePaymentError();
      }
    },
    handleScanComplete(val) {
      clearTimeout(this.scanTimer);
      this.scanTimer = setTimeout(() => {
        val = val.trim();
        if (!val) return;

        // 验证格式
        const isAlipay = /^(25|26|27|28|29|30)\d{14,22}$/.test(val);
        const isWechat = /^(10|11|12|13|14|15)\d{16}$/.test(val);

        if (!isAlipay && !isWechat) {
          this.$message.error('付款码格式错误');
          this.errorMessage = '付款码格式错误';
          this.scanStatus = 'error';
          this.paymentCode = '';
          this.startCountdown();
          return;
        }

        // 开始处理
        this.processPayment(val);
      }, 300);
    },
    handlePayDialogClosed() {
      this.resetScanner();
      if (this._blurHandler) {
        this.$refs.paymentCodeInput?.$el
            .querySelector('input')
            .removeEventListener('blur', this._blurHandler);
      }
    },
    handlePayDialogOpened() {
      this.resetScanner();
      this.$nextTick(() => {
        const input = this.$refs.paymentCodeInput;
        if (input) {
          // 双重聚焦确保Element UI组件接受焦点
          input.focus();
          input.$el.querySelector('input').focus();

          // 防止意外失去焦点（扫码枪场景专用）
          this._blurHandler = () => {
            setTimeout(() => input.$el.querySelector('input').focus(), 10);
          };
          input.$el.querySelector('input').addEventListener('blur', this._blurHandler);
        }
      });
    },
    resetScanner() {
      this.scanStatus = 'waiting';
      this.paymentCode = '';
      this.countdown = 5;
      this.errorMessage = '付款失败,请重试';
      clearInterval(this.timer);
      cancelAnimationFrame(this.animationFrameId);
      this.$nextTick(() => {
        const input = this.$refs.paymentCodeInput?.$el?.querySelector('input');
        if (input) {
          input.focus();
          input.select();
        }
      });
    },

    calculatePayments() {
      // ========== 新增：正则过滤所有金额字段 ==========
      const validateAmount = (value) => {
        const num = Number(value);
        // 允许空值或非负数
        return value === '' || (!isNaN(num) && num >= 0);
      };

      // 校验所有支付金额字段
      const amountFields = [
        Number(this.patientForm.total),
        Number(this.addForm.chsAmt),
        Number(this.addForm.bankAmt),
        Number(this.addForm.bebtAmt),
        Number(this.addForm.groupAmt),
        Number(this.addForm.patAmt),
        Number(this.rowData.price),
      ];

      if (!amountFields.every(validateAmount)) {
        this.$message.warning('请输入有效的正数金额');
        return; // 如果校验失败，终止计算
      }

      // ========== 原计算逻辑 ==========
      // 1. 获取应收金额（已通过校验，可直接转换）
      const total = Number(this.patientForm.total) || 0;

      // 2. 计算非现金支付总额（已通过校验，可直接转换）
      const nonCashPaid = [
        Number(this.addForm.chsAmt),
        Number(this.addForm.bankAmt),
        Number(this.addForm.bebtAmt),
        Number(this.addForm.groupAmt),
        Number(this.addForm.patAmt),
      ].reduce((sum, val) => sum + (Number(val) || 0), 0);

      // 3. 计算现金支付缺口
      const cashGap = Number(total) - Number(nonCashPaid);

      this.addForm = {
        ...this.addForm,
        cashAmt: Number(cashGap.toFixed(2)),      // 转回数字
        recdAmt: Number(Math.max(0, cashGap).toFixed(2)),
        change: Number(cashGap < 0 ? Math.abs(cashGap).toFixed(2) : 0),
        paidAmt: Number((nonCashPaid + Math.max(0, cashGap) - (Number(this.addForm.bebtAmt) || 0)).toFixed(2))
      };
    },

    getSelectedPath(node) {
      const path = [];
      let currentNode = node;

      while (currentNode?.data) {
        path.unshift(currentNode.data);
        currentNode = currentNode.parent;
      }

      return path;
    },

    getConditionByLevel(level) {
      const conditions = {
        2: 'area_p_code', // 省→市
        3: 'area_c_code', // 市→县
        4: 'area_d_code', // 县→镇
        5: 'area_t_code'  // 镇→乡
      };
      return conditions[level] || 'area_p_code';
    },

    async certnoMonitor2(val) {
      if (!val.certno) return;

      const certType = val.identityCard;
      const certLength = this.certLengthMap[certType];
      const certPattern = this.certPatterns[certType];

      // 长度验证
      if (val.certno.length !== certLength) {
        this.$message.error(`请输入${certLength}位证件号码`);
        return;
      }

      // 格式验证
      if (certPattern && !certPattern.test(val.certno)) {
        this.$message.error('证件号码格式不正确');
        return;
      }

      // 特殊证件处理（仅身份证）
      if (certType === 1) { // 居民身份证
        try {
          // 身份证存在性检查
          const res = await getDoesItExistSFZ({
            certNo: val.certno.toString()
          });

          if (res.data && val.certno !== this.patientChooseForm?.certno) {
            this.$message.error("该身份证在信息库中已经存在!");
            return;
          }

          // 解析身份证信息
          const genderDigit = parseInt(val.certno.charAt(16), 10);
          val.sex = genderDigit % 2 === 1 ? '1' : '2';

          // 计算年龄和出生日期
          const data = this.getAgeAndMonthsFromIdCard(val.certno);
          val.ageYear = data.years;
          val.ageMonth = data.months;
          val.brdy =
              val.certno.slice(6, 10) + '-' +
              val.certno.slice(10, 12) + '-' +
              val.certno.slice(12, 14);

        } catch (error) {
          console.error('身份证验证失败:', error);
          this.$message.error('身份证验证服务异常');
        }
      } else if (certType === '8') { // 武警证件
        val.sex = ''; // 清除非身份证的性别信息
      } else {
        // 其他证件类型清空自动计算字段
        val.sex = '';
        val.ageYear = '';
        val.ageMonth = '';
        val.brdy = '';
      }
    },

    async certnoMonitor(val) {
      if (!val.certno) return;

      const certType = this.patientForm.identityCard; // 使用相同的证件类型选择
      const certLength = this.certLengthMap[certType];
      const certPattern = this.certPatterns[certType];

      // 长度验证
      if (val.certno.length !== certLength) {
        this.$message.error(`请输入${certLength}位证件号码`);
        return;
      }

      // 格式验证
      if (certPattern && !certPattern.test(val.certno)) {
        this.$message.error('证件号码格式不正确');
        return;
      }

      // 特殊证件处理（仅身份证）
      if (certType === 1) { // 居民身份证
        try {
          // 身份证存在性检查
          const res = await getDoesItExistSFZ({
            certNo: val.certno.toString()
          });

          if (res.data && val.certno !== this.patientChooseForm?.certno) {
            this.$message.error("该身份证在信息库中已经存在!");
            return 1;
          }

          // 解析身份证信息
          const genderDigit = parseInt(val.certno.charAt(16), 10);
          val.sex = genderDigit % 2 === 1 ? '1' : '2';

          // 计算年龄和出生日期
          const data = this.getAgeAndMonthsFromIdCard(val.certno);
          val.ageYear = data.years;
          val.ageMonth = data.months;
          val.brdy =
              val.certno.slice(6, 10) + '-' +
              val.certno.slice(10, 12) + '-' +
              val.certno.slice(12, 14);

        } catch (error) {
          console.error('身份证验证失败:', error);
          this.$message.error('身份证验证服务异常');
        }
      } else if (certType === '8') { // 武警证件
        val.sex = ''; // 清除非身份证的性别信息
      } else {
        // 其他证件类型清空自动计算字段
        val.sex = '';
        val.ageYear = '';
        val.ageMonth = '';
        val.brdy = '';
      }
    },

    getAgeAndMonthsFromIdCard(idCard) {
      if (!idCard || idCard.length !== 18) return {years: 0, months: 0, birthday: ''};

      const birthStr = idCard.slice(6, 14); // 格式：YYYYMMDD
      const birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;

      const birthDate = new Date(birthday);
      if (isNaN(birthDate.getTime())) return {
        years: 0,
        months: 0,
        birthday: ''
      };

      // 2. 获取当前日期
      const today = new Date();

      // 3. 计算周岁
      let years = today.getFullYear() - birthDate.getFullYear();

      // 4. 计算月龄（总月数差）
      let months = (today.getFullYear() - birthDate.getFullYear()) * 12 +
          (today.getMonth() - birthDate.getMonth());

      // 5. 调整年龄和月龄（如果生日未到）
      if (
          today.getMonth() < birthDate.getMonth() ||
          (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
      ) {
        years--;
        months--;
      }

      // 6. 确保月龄为正数
      months = Math.max(0, months % 12); // 超过12个月的部分已计入周岁

      return {years, months, birthday};
    },

    async handleAddCelerityFiling() {
      const valid = await this.$refs.celerityFilingFormRef.validate();
      if (!valid) return;
      await withLoading(this, '数据提交中...')(async () => {
        this.celerityFilingForm.tel = this.celerityFilingForm.conerTel;
        this.celerityFilingForm.conerAddCode =
            this.celerityFilingForm.conerAddCodeArr.length > 0 ? this.celerityFilingForm.conerAddCodeArr[this.celerityFilingForm.conerAddCodeArr.length - 1] : '';
        const res = await addDocphr(this.celerityFilingForm);
        if (res.code === 200) {
          this.patientForm.patId = this.celerityFilingForm.name;
          await this.handleSearch(1);
          this.handleResetContract();
          this.$refs.celerityFilingFormRef.resetFields();
          this.celerityFilingDialogVisible = false;
        } else {
          this.$message.error(res.message)
        }
      });
    },

    handleCelerityFiling() {
      this.conerPleasett = '';
      this.celerityFilingDialogVisible = true;
    },

    async handleEditDocphr() {
      await withLoading(this, '数据提交中...')(async () => {
        this.patientForm.conerAddCode =
            this.patientForm.conerAddCodeArr.length > 0
                ? this.patientForm.conerAddCodeArr[this.patientForm.conerAddCodeArr.length - 1]
                : '';
        this.patientForm.thrNot = this.patientForm.thrNot ? 1 : 0;
        this.patientForm.age = this.patientForm.ageYear;
        this.patientForm.conerRltsId = this.patientForm.conerRltsId === '' ? null : this.patientForm.conerRltsId;
        console.log(this.patientForm, 'this.patientFormthis.patientFormthis.patientForm')
        const res = await editDocphr(this.patientForm);

        // 4. 处理响应
        if (res.code === 200) {
          this.patientForm.patId = this.patientForm.certno;
          await this.handleSearch();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    updateTimeSlot() {
      const now = new Date()
      const hours = now.getHours()
      const minutes = now.getMinutes()
      const totalMinutes = hours * 60 + minutes

      if (totalMinutes >= 450 && totalMinutes <= 720) { // 07:30-12:00
        this.patientForm.timeSlot = '1'
      } else if (totalMinutes >= 780 && totalMinutes <= 1080) { // 13:00-18:00
        this.patientForm.timeSlot = '2'
      } else if (totalMinutes >= 1140 && totalMinutes <= 1439) { // 19:00-23:59
        this.patientForm.timeSlot = '3'
      } else {
        this.patientForm.timeSlot = '1' // Outside defined slots
      }
    },

    handleCloseConfirmPay() {
      this.addForm = Object.assign({}, this.$options.data.call(this).addForm)
      this.addModalVisible = false;
    },

    async handleConfirmPay() {
      /*// 1. 验证挂账金额是否导致现金支付为负
      if (Number(this.addForm.bebtAmt) > (Number(this.addForm.cashAmt) + Number(this.addForm.groupAmt))) {
        return this.$message.warning("挂账金额不能超过应收金额");
      }
      // 2. 处理挂账情况
      if (this.paymentForm.bebtAmt > 0) {
        await this.getOnCreditList();
        this.onCreditDialogVisible = true;
        return;
      }*/

      await withLoading(this, '支付处理中...')(async () => {
        if (Math.abs(Number(this.addForm.cashAmt) - Number(this.addForm.recdAmt)) < 0.01) {
          this.addForm.groupAmt = Number(this.addForm.groupAmt)
          this.addForm.age = this.patientForm.thrNot === 0 ? this.patientForm.ageYear : 0;
          console.log(this.addForm, 'addFormaddFormaddFormaddFormaddForm')
          const res = await addRegisterList(this.addForm);
          if (res.code === 200) {
            /*if (this.addForm.chsAmt > 0){
              this.handleYbReservation(res.data.id);
            }*/
            if (this.addForm.groupAmt > 0) {
              this.payModalVisible = true;
              this.orderId = res.data;
              return;
            }
            this.handleCloseForm();
            this.loadData();
            this.addModalVisible = false;
          } else {
            this.$message.error(res.message)
          }
        } else {
          this.$message.warning("实收金额与应收金额不匹配");
        }
      });

    },

    async handleReservationSettle() {
      if (this.rowData === null) return this.$message.warning("请先选择医生进行挂号结算操作");
      if (this.patientForm.name === '') return this.$message.warning("请填写姓名");
      if (this.patientForm.doctor === null) return this.$message.warning("请选择科室和医生");
      await withLoading(this, '数据提交中...')(async () => {
        if (this.patientForm.thrNot === 0) {
          await this.handleEditDocphr();
        }
        const price = Number(this.rowData.price) || 0;
        this.addForm = {
          ...this.addForm,
          cashAmt: price,
          currentTotal: price,
          recdAmt: price,
          MoneyPay: price,
          receiveNumber: price,
          receivableNumber: price,
          receivableMoney: price,
          receivedMoney: price,
          feeType: 2,
          name: this.patientForm.name,
          patientId: this.patientForm.id,
          regDepId: this.rowData.deptId,
          regDoctorId: this.rowData.doctorId,
          rgstId: this.rowData.id,
          regMode: 1,
          regTypeId: this.rowData.registertypeId,
          regUserId: JSON.parse(localStorage.getItem('userInfo')).staffId
        };
        this.addModalVisible = true;
      });
    },

    handleCloseForm() {
      this.patientForm = Object.assign({}, this.$options.data.call(this).patientForm);
      this.celerityFilingForm = Object.assign({}, this.$options.data.call(this).celerityFilingForm);
      this.conerPleasett = '';
      this.isInputDisabled = false;
    },

    handleRowClick(row) {
      this.getRegisterType(row);
      this.rowData = JSON.parse(JSON.stringify(row));
      this.patientForm.registerType = row.registertypeId;
      this.patientForm.doctor = row.doctorId;
      this.patientForm.total = row.price;
      /*      this.patientForm.existNumber = row.useNum;
            this.patientForm.existNumber = row.remainingNum;*/
      console.log(row, 'rowrow')
    },

    handleCloseRegisterType() {
      this.tableData = [];
      this.loadData();
    },

    getRegisterTypeData() {
      this.tableData = this.tableData.filter(item => item.registertypeId === this.patientForm.registerType)
    },

    getTimeFrameData() {
      this.loadData();
    },

    getDoctorReservation(val) {
      this.tableData = this.tableData.filter(item => item.doctorId === val)
    },

    handleCloseDept() {
      this.patientForm.doctor = null;
      this.patientForm.department = null;
      this.patientForm.total = null;
      this.patientForm.existNumber = null;
      this.tableData = [];
    },

    handleCloseDoctor() {
      this.patientForm.doctor = null;
      this.doctorOptions = [];
      this.getClinicSchedule();
    },

    getTimeDetail(timeFrame) {
      return timeFrame === '1' ? '07:30-12:00' :
          timeFrame === '2' ? '13:00-18:00' :
              timeFrame === '3' ? '19:00-23:59' : '休息时间';
    },

    async getRegisterType(row) {
      if (this.registerOptions.length > 0) return;
      const res = await getRegisterType();
      this.registerOptions = res.data.map(item => {
        return {label: item.designation, id: item.id, odcost: item.odcost}
      })
    },

    async getClinicSchedule(val) {
      try {
        if (!this.patientForm.timeSlot) return this.$message.warning("请先选择时段！")
        const active = await getActiveList({
          deptId: this.userInfo.selDept,
          regTime: this.patientForm.registerDate.toString(),
          type: parseInt(this.patientForm.timeSlot)
        })
        if (active.data.length <= 0) return this.$message.error("该科室当前没有坐诊医生")
        await this.getDoctorList();
        console.log(this.doctorOptions, 'this.doctorOptionsthis.doctorOptionsthis.doctorOptions')
        this.tableData = await Promise.all(active.data.map(async item => {
          // 获取职称
          const matchedDoctor = this.doctorOptions.find(
              doctor => doctor.id === item.doctorId
          );

          // 添加防御性编程
          const titel = matchedDoctor
              ? this.profttlOption.find(t => t.id === parseInt(matchedDoctor.titel))?.label
              : '未知职称';

          // 返回处理后的对象
          return {
            ...item,
            professionalTitle: titel,
            timeFrame: this.patientForm.timeSlot === '1' ? '上午' :
                this.patientForm.timeSlot === '2' ? '下午' :
                    this.patientForm.timeSlot === '3' ? '晚上' : '',
            timeDetail: this.getTimeDetail(this.patientForm.timeSlot)
          };
        }));
        console.log(this.tableData)
      } catch (error) {
        console.error('获取排班数据失败:', error);
        this.$message.error('数据加载失败');
      }
    },

    async getDeptOfDoctor(val) {
      this.doctorOptions = [];
      const res = await getDeptOfDoctor({deptId: this.userInfo.selDept});
      this.doctorOptions = res.data.map(item => {
        return {label: item.fullName, id: item.id, titel: item.professionalTitle}
      })
    },

    async getDoctorList() {
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName, titel: item.professionalTitle}
      })
      /*      const res = await getDeptOfDoctor({deptId: this.patientForm.department});
            this.doctorOptions = res.data.map(item => {
              return {label: item.fullName, id: item.id, titel: item.professionalTitle}
            })*/
    },

    async getDeptList() {
      if (this.deptOptions.length > 0) return;
      const res = await getConsultingDepartment();
      this.deptOptions = res.data.map(item => {
        return {id: item.deptId, label: item.deptName}
      })
    },

    handleNameChangeCode(v, i) {
      switch (i) {
        case 1 :
          this.addUnitForm.pyCode =
              pinyin(this.addUnitForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
      }
    },

    async handleAddContractUnit() {
      await withLoading(this, '数据提交中...')(async () => {
        if (this.addUnitForm.id) {
          const res = await editContractUnit(this.addUnitForm);
          if (res.code === 200) {
            await this.getContuntList();
          } else {
            this.$message.error(res.message)
          }
        } else {
          const res = await addContractUnit(this.addUnitForm);
          if (res.code === 200) {
            await this.getContuntList();
          } else {
            this.$message.error(res.message)
          }
        }
        this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
        this.addUnitModalVisible = false;
      });
    },
    handleCancelContract() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = false;
    },
    submitForm() {
      this.$refs.addUnitRef.validate((valid) => {  // 注意这里的 ref 名称要匹配
        if (valid) {
          // 验证通过后的操作（如API请求）
          alert('表单验证成功！')
        } else {
          // 验证失败自动显示错误提示（ElementUI内置行为）
          return false
        }
      })
    },

    async handleEditContractUnit(item) {
      const res = await getContractUnit(item.id.toString())
      this.addUnitForm = res.data
      this.addUnitModalVisible = true;
    },

    handleSaveContractUnit() {
      this.addUnitForm = Object.assign({}, this.$options.data.call(this).addUnitForm)
      this.addUnitModalVisible = true;
    },

    handleClickRow(row) {
      this.patientChooseForm = row;
    },
    async handleChoosePatient() {
      this.isInputDisabled = false;

      try {
        await withLoading(this, '数据加载中...')(async () => {
          // 2. 处理身份证信息（包含年龄计算）
          console.log(this.patientChooseForm, 'this.patientChooseFormthis.patientChooseForm')
          const processIdCard = () => {
            // 允许身份证信息缺失，不抛出错误
            if (!this.patientChooseForm.certno?.trim()) {
              return {
                ageYear: null,     // 返回null或设置默认值
                ageMonth: null,    // 返回null或设置默认值
                brdy: null         // 返回null或设置默认值
              };
            }

            try {
              const ageInfo = this.getAgeAndMonthsFromIdCard(this.patientChooseForm.certno);
              return {
                ageYear: ageInfo.years,     // 映射到ageYear
                ageMonth: ageInfo.months,   // 映射到ageMonth
                brdy: ageInfo.birthday      // 映射到brdy
              };
            } catch (error) {
              console.error('身份证解析错误:', error);
              return {
                ageYear: null,
                ageMonth: null,
                brdy: null
              };
            }
          };

          const matchedUnit = this.contractUnitOption.find(
              item => item.id === this.patientChooseForm.phrUnt
          );
          // 3. 完整基础信息赋值（无省略任何字段）
          const assignBaseInfo = (ageData) => {
            const baseFields = {
              // 患者标识信息
              id: this.patientChooseForm.id || null,
              patId: this.patientChooseForm.patId || '',
              patientId: this.patientChooseForm.patientId || null,
              dregisterTableId: this.patientChooseForm.dregisterTableId || null,

              // 个人信息
              name: this.patientChooseForm.name || '',
              sex: this.patientChooseForm.sex?.toString() || '1',
              certno: this.patientChooseForm.certno || '',
              identityCard: this.patientChooseForm.identityCard || 1,
              naty: this.patientChooseForm.naty || 3,
              jobId: this.patientChooseForm.jobId || null,
              ntlyId: parseInt(this.patientChooseForm.ntlyId) || null,

              // 联系信息
              tel: this.patientChooseForm.tel || '',
              conerName: this.patientChooseForm.conerName || '',
              conerTel: this.patientChooseForm.conerTel || '',
              conerRltsId: this.patientChooseForm.conerRltsId || null,

              // 医疗信息
              thrNot: this.patientChooseForm.thrNot || 0,
              prhType: this.patientChooseForm.prhType || null,
              aiseId: this.patientChooseForm.aiseId || null,
              bloodNumber: this.patientChooseForm.bloodNumber || '',
              bloodType: this.patientChooseForm.bloodType || null,
              syspre: this.patientChooseForm.syspre || 0,
              diapre: this.patientChooseForm.diapre || 0,
              phrUnt: matchedUnit ? this.patientChooseForm.phrUnt : null,
              prhCostType: this.patientChooseForm.prhCostType || null,
              seedoctorcCount: null,
              seedoctorcType: null,

              // 地址信息
              naplAddName: this.patientChooseForm.naplAddName || '',
              conerAddName: this.patientChooseForm.conerAddName || '',

              // 注入计算出的年龄信息
              ...ageData  // 包含ageYear, ageMonth, brdy
            };

            Object.assign(this.patientForm, baseFields);
          };


          // 4. 完整行政区划处理（保持原有逻辑）
          const processRegionCodes = () => {
            const regionCode = this.patientChooseForm.naplAddCode?.toString() || '';
            const contactRegionCode = this.patientChooseForm.conerAddCode?.toString() || '';

            this.patientForm.naplAddCodeArr = [];
            this.patientForm.conerAddCodeArr = [];

            const regionProcessors = [
              {level: '省级', transform: c => this.formatRegionCode(c, 2, 10)},
              {level: '市级', transform: c => this.formatRegionCode(c, 4, 8)},
              {level: '县级', transform: c => this.formatRegionCode(c, 6, 6)},
              {level: '乡镇', transform: c => this.formatRegionCode(c, 9, 3)},
              {level: '村级', transform: c => c}
            ];

            regionProcessors.forEach(({level, transform}) => {
              this.patientForm.naplAddCodeArr.push(transform(regionCode));
              this.patientForm.conerAddCodeArr.push(transform(contactRegionCode));
            });
          };

          // 执行流程
          const ageData = processIdCard();  // 获取年龄数据
          assignBaseInfo(ageData);         // 赋值所有字段（包含年龄）
          processRegionCodes();            // 处理地址
          console.log(this.patientForm, 'this.patientFormthis.patientFormthis.patientFormthis.patientForm')
          await this.loadAndDisplayAddress();
          this.patientDialogVisible = false;
        });

      } catch (error) {
        this.$message.error(`操作失败: ${error.message}`);
        console.error('患者信息处理错误:', error);
      } finally {
        this.isInputDisabled = true;
      }
    },

    async handleSearch(connect) {
      await withLoading(this, '数据加载中...')(async () => {
        const res = await getDocphrList({condtion: this.patientForm.patId});
        if (connect === 1) {
          this.patientChooseForm = res.data[res.data.length - 1]
          await this.handleChoosePatient();
          return;
        }
        if (res.data.length > 1) {
          this.patientDialogVisible = true;
          this.patientTabelData = res.data;
          this.isInputDisabled = this.patientForm.patId != null;
          return;
        } else if (res.data.length <= 0) {
          this.$message.warning("没有搜索到相关患者!请在健康档案新增或点击下方快速建档!")
          return;
        }
        this.patientChooseForm = res.data[0];
        await this.handleChoosePatient()
        this.isInputDisabled = this.patientForm.patId != null;
      });
    },

    async dict() {
      const res = await dict();
      this.nationOption = res.data.natyEntities.map(item => {
        return {id: item.id, label: item.name}
      })
      this.certypeOption = res.data.certypeEntities.map(item => {
        return {id: item.id, label: item.name}
      })
      this.profttlOption = res.data.profttlEntities.map(item => {
        return {id: item.id, label: item.name}
      })
      console.log(this.profttlOption, 'profttlOptionprofttlOption')

      this.prhCostOption = res.data.prhCostType.map(item => {
        return {id: item.id, label: item.name}
      })

      this.prhTypeOption = res.data.prhType.map(item => {
        return {id: item.id, label: item.name}
      })
      this.jobOption = res.data.jobEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.rltsEntitiesOption = res.data.rltsEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.untAtteOption = res.data.unatteVo.map(item => {
        return {id: item.id, label: item.name}
      })

      this.ntlyOptions = res.data.country.map(item => {
        return {id: item.id, label: item.name}
      })
    },


    handleClear(res) {
      switch (res) {
        case 1:
          this.patientForm.province = ''
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          this.profttlOption = [];
          break;

        case 2:
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          break;
        case 3:
          this.patientForm.county = '';
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          break;

        case 4:
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          break;

        case 5:
          this.patientForm.village = '';
          this.villageOption = [];
          break;
      }
    },

    async getContuntList() {
      const res = await getContuntList();
      this.contractUnitOption = res.data.map(item => {
        return {id: item.id, label: item.name, code: item.code}
      })
    },
    /*---------数据源---------*/
    async loadData() {
      const res = await getActiveList({
        deptId: this.patientForm.department === null ? null : this.patientForm.department,
        regTime: this.patientForm.registerDate.toString(),
        type: parseInt(this.patientForm.timeSlot)
      })
      await this.getDoctorList();
      const processedData = await Promise.all(res.data.map(async item => {
        const matchedDoctor = this.doctorOptions.find(
            doctor => doctor.id === item.doctorId
        );
        const titel = matchedDoctor
            ? this.profttlOption.find(t => t.id === matchedDoctor.titel)?.label
            : '未知职称';
        return {
          ...item,
          professionalTitle: titel,
          price: Number(item.price).toFixed(2),
        };
      }));
      this.tableData = processedData.map(item => {
        return {
          ...item,
          amTime: item.smorningTime + '-' + item.emorningTime,
          pmTime: item.safternoonTime + '-' + item.eafternoonTime,
          nightTime: item.snightTime + '-' + item.enightTime
        }
      });
    },

    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 100; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串


      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 8; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 12;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadData();
    },
    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },
    formatRegionCode(code, prefixLength, zeroPadding) {
      if (!code || code.length < prefixLength) {
        return code || '';
      }
      return code.substring(0, prefixLength) + '0'.repeat(zeroPadding);
    },
    getColumnWidth(label, prop, tableData) {
      const minWidth = 100;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
    safeGetMappedValue(col, row, type) {

      const hiddenProps = new Set([
        'usedfrquId', 'sdoseCnt', 'prdCnt', 'prdDays', 'medcWayId', 'tcmCnt',
        'selfProe', 'skintstRslt', 'remark', 'remarks', 'rxDosCnt',
      ]);

      if (hiddenProps.has(col.prop)) {
        return ''; // 直接返回空字符串，不显示
      }
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },
    getRandom4Digits() {
      return Math.floor(1000 + Math.random() * 9000).toString();
    },
  }
}
</script>


<style lang="less" scoped>
.system-tabs /deep/ .el-tabs__content {
  padding: 0;
}

/* 方法2：使用 ::v-deep 选择器（推荐） */
.system-tabs ::v-deep .el-tabs__content {
  padding: 0;
}

/* 表格容器样式 */
.table-container {
  height: 70vh;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 表格样式 */
.el-table {
  width: 100% !important;
  margin: 0;
  padding: 0;
}

/* 底部按钮区域 */
.custom-dialog-footer {
  padding: 10px 0;
  background: #fff;
}

.main-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh; /* 占满整个屏幕高度 */
  overflow: hidden; /* 防止滚动条影响布局 */
}

.compact-form-box {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  background: #fff;
  border-bottom: 1px solid #e6e6e6; /* 分隔线 */
}

.table-container {
  flex: 1; /* 自动填充剩余空间 */
  width: 100%;
  overflow: auto; /* 表格内容过多时滚动 */
  padding: 10px;
  box-sizing: border-box;
  background: #fff;
}

.dialog-footer {
  text-align: right;
  margin-top: 25px;
  padding-right: 15px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 15px;
  border-top: 1px solid #e1e4e8;
}

::v-deep .el-cascader .el-input__inner::placeholder {
  color: var(--el-text-color-placeholder) !important; /* 使用官方变量 */
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.payment-summary {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 15px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  display: inline-block;
  width: 120px;
  text-align: left;
}

.form-section {
  background: white;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.payment-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.MedicenCata {
  height: 90vh;
  display: flex;
  flex-direction: column;
}


/* 表格容器 (90%) */
.table-container {
  flex: 1;
  overflow: auto;
  margin-right: 10px;
}

/* 挂号信息容器 (10%) */
.registration-container {
  flex: 0.1;
  display: flex;
  flex-direction: column;
  min-width: 150px; /* 确保最小宽度 */
}

.registration-box {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  background-color: #f5f7fa;
  height: 100%;
}

.data-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.data-row .label {
  width: 60px; /* 缩小标签宽度以适应更窄的容器 */
  font-size: 12px;
  color: #606266;
}

.data-row .el-input {
  flex: 1;
}

/* 底部区域样式 */
.footer-container {
  padding: 10px;
}


.footer-buttons {
  display: flex;
  justify-content: flex-end;
  padding: 0 10px;
}

.celerity-filing-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px; /* 增加与表单的距离 */
}

/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

.dialog {
  .addUnitDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }

  .patient-dialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}

.custom-dialog-footer {
  display: flex;
  justify-content: space-between; /* 左右两侧分开 */
  align-items: center; /* 垂直居中 */
}

.left-buttons,
.right-buttons {
  display: flex;
  gap: 10px; /* 按钮间距 */
}

/* 如果需要右侧按钮组靠右对齐 */
.right-buttons {
  margin-left: 100px;
}

/* 关键样式 */
.input-with-button .el-input-group__append {
  padding: 0; /* 移除默认内边距 */
}

.auto-height-button {
  height: 100% !important; /* 继承父容器高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 4px 4px 0 !important; /* 保持圆角匹配 */
}

/* 确保输入框和按钮高度统一 */
.input-with-button .el-input__inner {
  height: 40px; /* 调整这个值会同时改变按钮高度 */
}

.main {
  padding: 0 6px; /* 调整内边距 */
  display: flex;
  justify-content: space-between;
}


.data-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 70px;
  font-size: 13px;
}

.el-input {
  flex: 1;
}


.side-panel {
  width: 240px;
  padding: 10px;
  background: #f5f7fa;
}

.registration-box {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.data-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  width: 70px;
  font-size: 13px;
  color: #666;
  margin-right: 4px;
}

.el-input {
  flex: 1;
}

.el-input.is-disabled .el-input__inner {
  background-color: #f5f5f5;
  color: #666;
}

/* 新增样式 */
.register-group {
  width: 50%;
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

/* 调整原有分隔线位置 */
.divider-line {
  width: 100%;
}

/* 强制同行显示 */
.register-type + .clinic-room {
  margin-left: -8px; /* 补偿间距 */
}

/* 关键修复样式 */
.compact-form {
  /* 在原有样式基础上添加 */

  .register-type,
  .clinic-room {
    flex: 1; /* 平分剩余空间 */
    min-width: 240px; /* 最小宽度保证换行后对齐 */
    max-width: 50%; /* 最大不超过50% */

    /deep/ .el-form-item__content {
      width: calc(100% - 90px) !important; /* 匹配label宽度 */
    }
  }

  /* 强制同行显示 */

  .register-type + .clinic-room {
    margin-left: -8px; /* 补偿间距 */
  }

  /deep/ .el-form-item__content {
    margin-left: 0 !important; /* 消除ElementUI默认的左侧间距 */
    width: auto !important; /* 取消固定宽度 */
  }

  /deep/ .el-form-item__label {
    padding-right: 6px !important; /* 标签与输入框间距 */
    width: auto !important; /* 取消标签固定宽度 */
    flex: none !important; /* 禁用flex自动分配 */
  }

  .el-form-item {
    /* 调整整体间距 */
    gap: 4px; /* 标签与控件间距 */

    /* 微调对齐方式 */
    align-items: baseline;
  }

  /* 特殊处理复选框 */

  .el-checkbox {
    margin-left: 2px;

    /deep/ .el-checkbox__label {
      display: none; /* 隐藏默认标签 */
    }
  }

  /* 输入框尺寸补偿 */

  .el-input--mini {
    line-height: 28px;

    /deep/ .el-input__inner {
      padding: 0 8px;
    }
  }
}

.compact-form-box {
  height: auto !important; /* 改为自适应高度 */
}

.compact-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px; /* 行列间距 */

  .el-form-item {
    margin: 0;
    display: inline-flex;
    align-items: center;

    /* 标签对齐 */

    /deep/ .el-form-item__label {
      line-height: 28px;
      padding-right: 4px;
    }

    /* 表单控件通用样式 */

    .el-input,
    .el-select,
    .el-date-editor {
      width: 100px; /* 默认宽度 */
    }

    /* 特定字段宽度调整 */

    &[label="性别:"] .el-select {
      width: 70px;
    }


    &[label="职业:"] .el-select {
      width: 130px;
    }

    &[label="病员费别:"] .el-select,
    &[label="病员类型:"] .el-select {
      width: 135px;
    }

    &[label="联系电话:"] .el-input {
      width: 135px;
    }


    &[label="挂号类别:"] .el-select,
    &[label="诊室:"] .el-select {
      width: 300px;
    }

    /* 年龄输入组 */

    .age-input-group {
      display: flex;
      align-items: center;

      .el-input {
        width: 32px !important;

        & + .age-unit {
          margin: 0 2px;
        }
      }
    }

    /* 地址输入组 */

    .age-select-address {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-input {
        width: 60px !important;

        &:nth-last-child(2) {
          width: 150px !important;
        }

        /* 乡镇输入框 */
      }
    }
  }

  /* 分隔线样式 */

  .divider-line {
    width: 100%;
  }
}


.divider-line {
  height: 1px;
  background-color: #ebeef5;
}

.compact-form-box {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 12px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.compact-form {
  font-size: 12px;
}

.el-form-item {
  margin-bottom: 5px;
}

.age-unit {
  margin: 0 5px;
  color: #909399;
  font-size: 12px;
}

.MedicenCata {
  width: 100%;

  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    .header-icon {
      display: flex;
      align-items: center;
    }
  }

  .main {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>